<template>
  <el-container style="margin-top: 10px">
    <el-header>
      <el-card style="height: 75px">
        <el-form :inline="true">
          <!-- <el-button
            icon="el-icon-plus"
            size="mini"
            type="primary"
            @click="topAddChapter"
          >添加子课题</el-button> -->

          <!-- <el-button
            icon="el-icon-plus"
            size="mini"
            type="primary"
          >批量导入
          </el-button> -->

          <el-form-item label=""
                        style="margin-left: 20px">
            <el-input v-model="chapterName"
                      placeholder="课程名称搜索"
                      size="mini" />
          </el-form-item>

          <el-button circle
                     type="primary"
                     icon="el-icon-search"
                     @click="searchClass" />
          <el-select v-model="teacher_id"
                     :disabled="selectDisabled"
                     placeholder="配置主讲老师"
                     @change="setTeachingTeacher">
            <el-option v-for="item in teacherlist"
                       :key="item.id"
                       size="mini"
                       :label="item.name"
                       :value="item.id" />
          </el-select>
          <el-button :disabled="selectDisabled"
                     type="primary"
                     style="margin-left：10px;"
                     @click="dialogVisible = true">配置评价问题</el-button>
        </el-form>

      </el-card>
    </el-header>

    <el-main>
      <el-card>
        <el-table v-loading="loading"
                  :data="classList"
                  @selection-change="selectionChange">
          <el-table-column type="selection"
                           width="55" />
          <el-table-column prop="name"
                           label="课题名"
                           align="center"
                           show-overflow-tooltip />
          <el-table-column align="center"
                           prop="description"
                           label="课题介绍"
                           show-overflow-tooltip />
          <el-table-column align="center"
                           prop="teacher_name"
                           label="主讲老师" />
          <el-table-column label="上课时间"
                           align="center">
            <template slot-scope="scope">
              <div>
                {{ scope.row.time_limit }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           prop="address"
                           label="上课地点"
                           show-overflow-tooltip />
          <el-table-column align="center"
                           label="上课人数">
            <template slot-scope="scope">
              <div>
                {{ scope.row.current_study_num }}/{{ scope.row.max_study_num }}
              </div>
            </template>
          </el-table-column>
          <el-table-column width="400px"
                           label="操作"
                           align="center">
            <template slot-scope="scope">
              <el-button size="mini"
                         type="primary"
                         icon="el-icon-edit"
                         @click="navto(scope.row.chapter_id)">查看报名</el-button>

              <!-- <el-button size="mini"
                         type="primary"
                         icon="el-icon-edit"
                         @click="hanldePreview(scope.row.chapter_id)">详情</el-button> -->

              <el-button size="mini"
                         type="danger"
                         icon="el-icon-delete"
                         @click="handleDeleteAdminUser(scope.row.id)">不讲该课题</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>

    <el-footer style="height: 85px">
      <el-card>
        <el-pagination style="text-align: center;"
                       :current-page="page"
                       :page-sizes="[10, 20, 30, 40]"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total"
                       background
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange" />
      </el-card>
    </el-footer>
    <!-- 添加 -->
    <el-dialog title="添加课程"
               :visible.sync="addClassVisible"
               width="700px"
               @close="dialogClose">
      <el-form ref="addAdminUserForm"
               :model="addChapterData"
               :rules="roles">
        <el-form-item label="课题名"
                      :label-width="formLabelWidth"
                      prop="name">
          <el-input v-model="addChapterData.name"
                    style="width: 300px"
                    placeholder="请输入课题名称" />
        </el-form-item>
        <el-form-item label="课题介绍"
                      :label-width="formLabelWidth"
                      prop="description">
          <el-input v-model="addChapterData.description"
                    style="width: 300px"
                    placeholder="请输入课题介绍" />
        </el-form-item>

        <el-form-item label="上课时间段"
                      :label-width="formLabelWidth">
          <!-- <el-time-picker
            is-range
            selectableRange='00:00 - 24:00'
            format='HH:mm'
            v-model="addChapterData.classTime"
            value-format='HH:mm'
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围">
          </el-time-picker> -->
          <el-date-picker v-model="addChapterData.classTime"
                          format="yyyy-MM-dd HH:mm"
                          value-format="yyyy-MM-dd HH:mm"
                          type="datetimerange"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          placeholder="选择时间范围">>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开始时间"
                      :label-width="formLabelWidth">
          <el-date-picker v-model="addChapterData.start_date"
                          value-format="yyyy-MM-dd"
                          type="date"
                          placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="最后报名时间"
                      :label-width="formLabelWidth">
          <el-date-picker v-model="addChapterData.end_date_apply"
                          value-format="yyyy-MM-dd"
                          type="date"
                          placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="最迟取消报名时间"
                      :label-width="formLabelWidth">
          <el-date-picker v-model="addChapterData.end_date_cancel"
                          value-format="yyyy-MM-dd"
                          type="date"
                          placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="上课人数"
                      :label-width="formLabelWidth"
                      prop="max_study_num">
          <el-input v-model="addChapterData.max_study_num"
                    style="width: 300px" />
        </el-form-item>
        <el-form-item label="上课地点"
                      :label-width="formLabelWidth"
                      prop="address">
          <el-input v-model="addChapterData.address"
                    style="width: 300px" />
        </el-form-item>
        <el-form-item label="课题排序"
                      :label-width="formLabelWidth"
                      prop="c_id">
          <el-input v-model="addChapterData.c_id"
                    style="width: 300px" />
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="addClassVisible = false">取 消</el-button>
        <el-button type="primary"
                   :disabled="disabled"
                   @click="createChapter">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择课题需配置的问题（多选）"
               :visible.sync="dialogVisible"
               width="60%"
               :before-close="handleCloseSubject">
      <template>
        <el-checkbox v-model="checkAll"
                     :indeterminate="isIndeterminate"
                     @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;" />
        <el-checkbox-group v-model="checkedCities"
                           @change="handleCheckedCitiesChange">
          <el-checkbox v-for="city in commentList"
                       :key="city.id"
                       :label="city.id">{{ city.question }}</el-checkbox>
        </el-checkbox-group>
      </template>

      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="SujectYes">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看课后评价内容"
               :visible.sync="subjectVisible"
               width="60%"
               @close="seeSubjectClose">
      <div class="title">
        <div class="left">
          问题
        </div>
        <div class="right">
          选项
        </div>
      </div>
      <div style="overflow: auto;height:500px">
        <div v-for="(item,index) in QuestionList"
             :key="index"
             class="ans">
          <div v-if="item.answer_type ==1"
               class="item">
            <div class="item_title">{{ item.title }}{{ item.pick_type==1?'（单选）':'（多选）' }}</div>
            <div class="item_right">
              <div v-for="(item2,index2) in item.details"
                   :key="index2"
                   class="item_right_item">
                <div class="item_text">
                  {{ item2.text }}
                </div>
              </div>
            </div>

          </div>
          <div v-if="item.answer_type ==2"
               class="item">
            <div class="item_title">{{ item.title }}（问答题）</div>
            <div class="item_right">
              <div class="item_right_item">
                <div class="item_text">
                  无
                </div>
              </div>
            </div>
          </div>

        </div>

      </div>
    </el-dialog>
  </el-container>
</template>

<script>
// import { teacherClass } from '@/api/teacher.js'
import { getToken } from '@/utils/auth'
import { teacherClass } from '@/api/teacher'
import { getChapterInfo, updateChapter, createChapter, ishowChapter, teacherForChapter, setTeachingTeacher } from '@/api/class'
import { delTeachRecord } from '@/api/teacher'
import { getCommentList2, getQuestionList, setQuestion } from '@/api/otherAPI.js'
const baseUrl = process.env.VUE_APP_BASE_API
export default {
  data () {
    return {
      teacherlist: [],
      value: '请选择老师',
      teacher_id: '',
      selectTeacher_id: '',
      selectUser: [],
      selectDisabled: true,
      disabled: false,
      loading: false,
      chapterName: '',
      createOrUpdate: '',
      addClassVisible: false,
      baomingVisible: false,
      dialogVisible: false, // 谈出框评价
      checkAll: false, // 是否全选
      checkedCities: [], // 选中的
      commentList: [], // 全部选择
      commentIdList: [], // 全部的id选择
      subjectVisible: false, // 查看问题列表是否
      isIndeterminate: true,
      QuestionList: [], // 问题列表
      addChapterData: {
        course_id: '',
        description: '',
        name: '',
        avatar: '',
        max_study_num: '',
        start_date: '',
        classTime: '',
        end_date_apply: '',
        end_date_cancel: '',
        address: '',
        c_id: ''
      },
      classList: [],
      total: 0,
      page: 1,
      pageSize: 10,
      upload_url: baseUrl + '/admin/user/uploadImage',
      header: {
        Authorization: getToken()
      },
      formLabelWidth: '200px',
      recommendList: [{ 'label': '课程1', 'value': '1' }, { 'label': '课程2', 'value': '2' }, { 'label': '课程3', 'value': '3' }],
      roles: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入课程介绍', trigger: 'blur' }
        ],
        start_date: [
          { required: true, message: '开始时间必填', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '上课地址必填', trigger: 'blur' }
        ],
        avatar: [
          { required: true, message: '课程图片必填', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.selectTeacher_id = this.$route.query.id
    this.teacherClass()
    this.teacherForChapter()
    this.getCommentList()
  },
  methods: {
    getQuestionList (id) {
      var data = {
        chapter_id: id
      }
      this.loading = true
      getQuestionList(data).then(res => {
        this.subjectVisible = true
        this.QuestionList = res.data
        console.log(res.data, 'getQuestionList')
        this.loading = false
      }).catch(response => {
        this.dialogVisible = false
        this.loading = false
        this.$message.error(response.msg)
      })
    },
    seeSubjectClose () {
      // 关闭 设置的问题
      this.subjectVisible = false
      this.QuestionList = []
    },
    getCommentList () {
      this.loading = true
      const params = {

      }
      getCommentList2(params).then(res => {
        this.commentList = res.data,
          res.data.map((val) => {
            [
              this.commentIdList.push(val.id)
            ]
          })
        this.checkedCities = []
        this.loading = false
      })
    },
    SujectYes () {
      // this.dialogVisible = false
      console.log(this.checkedCities.toString(), 'checkedCities')
      if (this.selectUser.length) {
        const data = {
          question_ids: this.checkedCities.toString(),
          chapter_ids: this.selectUser
        }
        setQuestion(data).then(res => {
          this.$message.success(res.msg)
          this.checkAll = false
          this.getCommentList()
          this.dialogVisible = false
        }).catch(err => {
          this.dialogVisible = true
          this.$message.error(response.msg)
        })
      }
    },
    handleCheckAllChange (val) {
      console.log(val, 'val')
      this.checkedCities = val ? this.commentIdList : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange (value) {
      console.log(value, 'value')
      const checkedCount = value.length
      this.checkAll = checkedCount === this.commentList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.commentList.length
    },
    handleCloseSubject (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },
    uploadSuccess (response, file, fileList) {
      if (response.code == 200) {
        this.addChapterData.avatar = response.data.url
      } else {
        this.$message.error(response.msg)
      }
    },
    beforeUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    topAddChapter () {
      this.addClassVisible = true
      this.createOrUpdate = 'create'
    },
    selectionChange (e) {
      console.log(e)
      this.selectUser = []
      e.forEach(item => {
        this.selectUser.push(item.id)
      })
      this.selectUser = this.selectUser.join(',')
      if (this.selectUser.length) {
        this.selectDisabled = false
      } else {
        this.selectDisabled = true
      }
    },
    setTeachingTeacher (e) {
      console.log(e)
      if (this.selectUser.length) {
        const data = {
          teacher_id: e,
          chapter_ids: this.selectUser
        }
        setTeachingTeacher(data).then(res => {
          this.$message.success(res.msg)
          this.teacherClass()
        })
      }
    },
    teacherForChapter () {
      teacherForChapter().then(res => {
        this.teacherlist = res.data
      })
    },
    teacherClass () {
      this.loading = true
      const params = {
        teacher_id: this.selectTeacher_id,
        page: this.page,
        page_size: this.pageSize
      }
      teacherClass(params).then(res => {
        this.classList = res.data.list
        this.total = res.data.paginate.total
        this.loading = false
      }).catch(res => {
        this.loading = false
      })
    },
    searchClass () {
      this.teacherClass()
    },
    createChapter () {
      this.$refs.addAdminUserForm.validate(valid => {
        if (!valid) {
          return false
        }
        this.disabled = true
        this.addChapterData.classTime = this.addChapterData.classTime.toString()
        if (this.createOrUpdate == 'create') {
          createChapter(this.addChapterData).then(res => {
            this.$message.success(res.msg)
            this.addClassVisible = false
            this.teacherClass()
          }).catch(err => {
            this.addChapterData.classTime = this.addChapterData.classTime.split(',')
            this.addClassVisible = false
          })
        } else {
          // 否则就是更新修改
          updateChapter(this.addChapterData).then(res => {
            this.$message.success(res.msg)
            this.addClassVisible = false
            this.teacherClass()
          }).catch(err => {
            this.addChapterData.classTime = this.addChapterData.classTime.split(',')
            this.addClassVisible = false
          })
        }
      })
    },
    switchChange (scope) {
      console.log(scope)
      const obj = { chapter_id: scope.id, is_show: '' }
      if (!scope.is_show) {
        obj.is_show = '2'
      } else {
        obj.is_show = '1'
      }
      ishowChapter(obj).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
          this.teacherClass()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleUploadImages () { },
    handleSizeChange () { },
    handleCurrentChange () {

    },
    hanldePreview (id) {
      this.addClassVisible = true
      this.createOrUpdate = 'update'
      const obj = { chapter_id: id }
      getChapterInfo(obj).then(res => {
        this.addChapterData = res.data
        console.log(res.data, 'res.data')
        this.addChapterData.classTime = res.data.classTime.split(',')
        this.addChapterData.chapter_id = res.data.id
      })
    },
    /**
     * 删除课程
     */
    handleDeleteAdminUser (id) {
      this.$confirm('确认删除,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 如果点击了确定 则执行的逻辑
        delTeachRecord({ id: id }).then(res => {
          this.$message.success(res.msg)
          this.teacherClass()
        })
      })
    },
    dialogClose () {
      this.disabled = false
      this.addChapterData = {
        start_date: '',
        end_date: '',
        description: '',
        name: '',
        avatar: '',
        sort: 0
      }
    },
    navto (option) {
      this.$router.push({ path: '../class-management/class-baoming?id=' + option })
    }
  }
}
</script>

<style scoped="scoped">
img {
  width: 100px;
  height: 100px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  object-fit: contain;
  width: 178px;
  height: 178px;
  display: block;
}
.title {
  width: 100%;
  display: flex;
  align-items: center;
  padding: 10px;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #dddddd;
}
.title .left {
  width: 30%;
}
.title .right {
  width: 70%;
}
.ans {
  width: 100%;
  text-align: center;
  font-size: 16px;
  line-height: 30px;
  border-bottom: 1px solid #dddddd;
}
.ans .item {
  display: flex;
  align-items: stretch;
}
.ans .item .item_title {
  width: 30%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 5px;
}
.ans .item .item_right {
  width: 70%;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #dddddd;
}
.ans .item .item_right .item_right_item {
  display: flex;
}
.ans .item .item_right .item_right_item .item_text {
  border-bottom: 1px solid #dddddd;
  padding: 5px;
  text-align: left;
  width: 100%;
}
.ans .item .item_right .item_right_item .item_select {
  width: 20%;
  border-left: 1px solid #dddddd;
  border-bottom: 1px solid #dddddd;
}
</style>
